package org.lex.dbq.model.service;

import java.io.IOException;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.Set;

import org.lex.dbq.model.bo.DefaultDriver;
import org.lex.dbq.model.bo.DriverConfig;
import org.lex.dbq.model.conf.Conf;
import org.lex.dbq.model.conf.ConfLoader;

public class DriverService extends CommonService<DriverConfig> {
	private static final DriverService INSTANCE = new DriverService();

	public static DriverService getInstance() {
		return INSTANCE;
	}

	public synchronized void store() throws IOException {
		ConfLoader.storeDrivers(Conf.DRIVERS_CONF_FILE, this.getAllObjects());
	}

	private DriverService() {
		load();
	}

	protected void load() {
		// profile
		ConfLoader.loadDrivers(Conf.DRIVERS_CONF_FILE, this);
		// system
		log.debug("load system drivers:");
		for (Enumeration<Driver> drivers = DriverManager.getDrivers(); drivers.hasMoreElements();) {
			Driver driver = drivers.nextElement();
			String className = driver.getClass().getName();
			log.info("System Driver: " + className);

			DriverConfig dc = new DriverConfig();
			dc.setDynamic(true);
			dc.setDescription("Dynamic System Driver");

			Set<DefaultDriver> set = ServiceFactory.getDefaultDriversService().getDrivers(className);
			if (false == set.isEmpty()) {
				DefaultDriver first = set.iterator().next();
				dc.setName(first.getName());
				dc.setClassName(first.getDriverClassName());
			} else {
				dc.setName(className);
				dc.setClassName(className);
			}
			this.add(dc);
		}
	}
}
